#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
sys.path.insert(0,'/home/liuyue/svn/wan/')
sys.path.insert(0,'/opt/web/')
from Tools import getPid
from Tools import connectMySQL 
import json
from util import cache, settings
import logging


def getOS(): 
    os_json = {}
    if not os_json :
        db = connectMySQL.connMySQL_mobileProduction()
        sql = 'SELECT id, name FROM `s_os`'
        logging.info(sql)
        c = db.cursor()
        c.execute(sql)  
        res = c.fetchall()
        for x in res:
            os_json[x[0]] = x[1]
        
        c.close()
        db.close()
        
        #cache.add('os_json', os_json, settings.cache_expire_S)
    
    return os_json
    
def getPidType(): 
#    pidtype_json = cache.get('pidtype_json') or {}
#    if not pidtype_json:
#        db = connectMySQL.connMySQL_mobileProduction()
#        sql = 'SELECT id, pid_type FROM `s_partner_pid_type`'
#        c=db.cursor()
#        c.execute(sql)
#        res= c.fetchall()
#        for x in res:
#            pidtype_json[x[0]] = x[1]
#        
#        cache.add('pidtype_json', pidtype_json, settings.cache_expire_S)
    pidtype_json = {}
    
    return pidtype_json

def getPromoFactoryName_copy(): 
    resjson = {}
    if not resjson:
        results = []
        db = connectMySQL.connMySQL_mobileProduction()
        c=db.cursor()        
        sql = "SELECT id, name FROM s_factory WHERE id IN ( SELECT f_id FROM  `s_partner_new` WHERE  `partner_mode` =2 and pid_stat=1)"
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        for x in res:
            results.insert(0, {'fid':x[0], 'name':x[1]})
        #test = {"items":[{"fid":"5", "name":"多普达 HTC"},{"fid":"14", "name":"优酷 youku"},{"fid":"15", "name":"中国移动MMarket CMCC Common Edition"},{"fid":"33", "name":"机锋网 Gfan"},{"fid":"45", "name":"掌软网 zruan"},{"fid":"46", "name":"安卓软件园 bestapk"},{"fid":"53", "name":"掌上应用汇 yingyonghui"},{"fid":"58", "name":"天网 tianwang"},{"fid":"96", "name":"freewap"},{"fid":"110", "name":"oppo"},{"fid":"113", "name":"sharp"},{"fid":"126", "name":"宝软"},{"fid":"130", "name":"泡椒"},{"fid":"133", "name":"电信"},{"fid":"136", "name":"移动"},{"fid":"140", "name":"通用"},{"fid":"143", "name":"联通"},{"fid":"144", "name":"TCL"},{"fid":"145", "name":"万普世纪"},{"fid":"146", "name":"有米广告"},{"fid":"147", "name":"腾讯"},{"fid":"149", "name":"洋浦科技"},{"fid":"151", "name":"乐玩中国"},{"fid":"152", "name":"138hi"},{"fid":"153", "name":"多么市场"},{"fid":"154", "name":"HOT市场"},{"fid":"155", "name":"安卓巴士"},{"fid":"156", "name":"zol在线"},{"fid":"157", "name":"历趣市场"},{"fid":"158", "name":"35797"},{"fid":"160", "name":"G友网"},{"fid":"162", "name":"手机中国"},{"fid":"163", "name":"木蚂蚁"},{"fid":"164", "name":"tompda"},{"fid":"165", "name":"虫洞"},{"fid":"166", "name":"十字猫"},{"fid":"167", "name":"魅锋"},{"fid":"168", "name":"手机软件园"},{"fid":"169", "name":"卓越手机网"},{"fid":"171", "name":"下载吧"},{"fid":"172", "name":"天涯"},{"fid":"173", "name":"手游155"},{"fid":"174", "name":"安致中文网"},{"fid":"175", "name":"手游5yy"},{"fid":"176", "name":"魅族溜"},{"fid":"178", "name":"绿软"},{"fid":"179", "name":"格瓦拉生活网"},{"fid":"180", "name":"H&M"},{"fid":"182", "name":"3G加油站"},{"fid":"183", "name":"精品市场"},{"fid":"186", "name":"哇麦"},{"fid":"188", "name":"123hw"},{"fid":"189", "name":"天空"},{"fid":"190", "name":"哇噻"},{"fid":"191", "name":"网讯安卓技术有限公司"},{"fid":"192", "name":"掌上书院"},{"fid":"193", "name":"亿优市场"},{"fid":"200", "name":"当乐"},{"fid":"201", "name":"3G泡泡 "},{"fid":"203", "name":"宜搜 "},{"fid":"204", "name":"公信市场"},{"fid":"207", "name":"潇湘晨报"},{"fid":"209", "name":"劲手"},{"fid":"210", "name":"卓恰"},{"fid":"216", "name":"恩度网"},{"fid":"218", "name":"第一手机市场"},{"fid":"219", "name":"蜘蛛市场"},{"fid":"223", "name":"巴士商店"},{"fid":"224", "name":"飞鹏网"},{"fid":"225", "name":"安卓软件分享社区"},{"fid":"226", "name":"华军软件园"},{"fid":"227", "name":"安智市场"},{"fid":"228", "name":"3G市场"},{"fid":"229", "name":"手机乐园"},{"fid":"230", "name":"多特软件站"},{"fid":"231", "name":"天极下载"},{"fid":"232", "name":"安卓之家"},{"fid":"233", "name":"安卓中文网"}]}
        
        c.close()
        db.close()
        
        resjson = {"status": "success", "items":results}
        #cache.add('PromoFactoryName_json', resjson, settings.cache_expire_S)
    
    return resjson

def getPidFactoryName(_btype):
    
    resjson = {}
    
    bt_sql = ""
    
    if _btype == "video":
        bt_sql = "  2 "
    if _btype == "paike":
        bt_sql = "  4 "
    
    if not resjson:
        results = []
        #select f.id as fid, o.id as oid, o.name_cn as oname, f.name as fname from s_os as o, s_factory as f, (SELECT distinct f_id,   os_id FROM  `s_partner_new` WHERE  `s_partner_pid_type` =10) a where o.id = a.os_id and f.id = a.f_id
        db = connectMySQL.connMySQL_mobileProduction()
        c=db.cursor()
        sql = "select f.id as fid, f.name_cn as fname, o.id as oid, o.name as oname,a.device_type from s_os as o, s_factory as f, (SELECT distinct f_id,   os_id,device_type FROM  `s_partner_new` WHERE  `partner_mode` =1 and pid_stat=1 and business_type = %s )  a where o.id = a.os_id and f.id = a.f_id  " % bt_sql
        print sql
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        for x in res:
            
            if x[4] == 1:
                type_1 = "phone"
            if x[4] == 2:
                type_1 = "pad"
            results.insert(0, {'fid':x[0], 'fname':x[1], 'osid':x[2], 'os': x[3],'type':type_1 })
        
        c.close()
        db.close()
        
        resjson = {"items":results}
        #cache.add('FactoryName_json', resjson, settings.cache_expire_S)
    
    return resjson
    
def getPromoFactoryName(_btype,_ftype):
    #test = {"items":[{"os":"Android", "fname":"华为 huawei", "fid":"2"},{"os":"Android", "fname":"多普达 HTC", "fid":"5"},{"os":"Android", "fname":"联想 lenovo", "fid":"10"},{"os":"Android", "fname":"三星 SAMSUNG", "fid":"12"},{"os":"Android", "fname":"优酷 youku", "fid":"14"},{"os":"Android", "fname":"天宇 K-Touch", "fid":"16"},{"os":"Android", "fname":"点心OS Dianxin", "fid":"29"},{"os":"Android", "fname":"LG", "fid":"75"},{"os":"Android", "fname":"MOTO", "fid":"77"},{"os":"Android", "fname":"oppo", "fid":"110"},{"os":"Android", "fname":"TCL", "fid":"144"},{"os":"Android", "fname":"索尼", "fid":"159"},{"os":"Android", "fname":"海尔", "fid":"161"},{"os":"Android", "fname":"海尔", "fid":"161"},{"os":"Android", "fname":"步步高", "fid":"170"},{"os":"Android", "fname":"酷派", "fid":"177"},{"os":"Android", "fname":"壹人壹本", "fid":"181"},{"os":"Android", "fname":"小米科技", "fid":"184"},{"os":"Android", "fname":"炬力", "fid":"185"},{"os":"Android", "fname":"康佳", "fid":"187"},{"os":"Android", "fname":"金立", "fid":"194"},{"os":"Android", "fname":"天语", "fid":"196"},{"os":"Android", "fname":"宏基", "fid":"197"},{"os":"Android", "fname":"广东移动", "fid":"198"},{"os":"Android", "fname":"海信", "fid":"199"},{"os":"Android", "fname":"万利达", "fid":"202"},{"os":"Android", "fname":"驰为", "fid":"205"},{"os":"Android", "fname":"博泰", "fid":"206"},{"os":"Android", "fname":"网合", "fid":"208"},{"os":"Android", "fname":"中兴", "fid":"211"},{"os":"Android", "fname":"杰拓", "fid":"213"},{"os":"Android", "fname":"大唐", "fid":"215"},{"os":"Android", "fname":"大唐", "fid":"215"},{"os":"Android", "fname":"高通", "fid":"217"},{"os":"bada", "fname":"三星 SAMSUNG", "fid":"12"},{"os":"java", "fname":"天奕达", "fid":"212"},{"os":"MTK", "fname":"MTK MTK", "fid":"18"},{"os":"MTK", "fname":"oppo", "fid":"110"},{"os":"MTK", "fname":"TCL", "fid":"144"},{"os":"MTK", "fname":"步步高", "fid":"170"},{"os":"MTK", "fname":"奥克斯", "fid":"214"},{"os":"Other", "fname":"诺基亚 nokia", "fid":"3"},{"os":"Other", "fname":"黑莓 blackberry", "fid":"26"},{"os":"unknown", "fname":"华为 huawei", "fid":"2"},{"os":"unknown", "fname":"爱国者 aigo", "fid":"20"},{"os":"unknown", "fname":"TCL", "fid":"144"},{"os":"Windows Phone", "fname":"多普达 HTC", "fid":"5"},{"os":"Windows Phone", "fname":"三星 SAMSUNG", "fid":"12"},{"os":"Windows Phone", "fname":"天宇 K-Touch", "fid":"16"},{"os":"Windows Phone", "fname":"通用", "fid":"140"}]}
    resjson = {}
    
    bt_sql = ""
    
    ft_sql = ""
    
    if _btype == "video":
        bt_sql = "  2 "
    if _btype == "paike":
        bt_sql = "  4 "
        
    if _ftype == "8":
        ft_sql = "  8 "
    if _ftype == "2":
        ft_sql = "  2 "
    
    if not resjson:
        results = []
        #select f.id as fid, o.id as oid, o.name_cn as oname, f.name as fname from s_os as o, s_factory as f, (SELECT distinct f_id,   os_id FROM  `s_partner_new` WHERE  `s_partner_pid_type` =10) a where o.id = a.os_id and f.id = a.f_id
        db = connectMySQL.connMySQL_mobileProduction()
        c=db.cursor()
        sql = "select f.id as fid, f.name_cn as fname, o.id as oid, o.name as oname,a.device_type,a.partner_mode from s_os as o, s_factory as f, (SELECT distinct f_id,   os_id,device_type,partner_mode FROM  `s_partner_new` WHERE   pid_stat=1 and business_type = %s and partner_mode = %s ) a where o.id = a.os_id and f.id = a.f_id " % (bt_sql,ft_sql)
        print sql
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        for x in res:
            
            if x[4] == 1:
                type_1 = "phone"
            if x[4] == 2:
                type_1 = "pad"
            type_2 = 1    
            if x[5] == 8:
                type_2 = 8
            if x[5] == 2:
                type_2 = 2
                
            results.insert(0, {'fid':x[0], 'fname':x[1], 'osid':x[2], 'os': x[3],'type':type_1,'ftype':type_2 })
        
        c.close()
        db.close()
        
        resjson = {"items":results}
        #cache.add('FactoryName_json', resjson, settings.cache_expire_S)
    
    return resjson

def getFactoryName():
    factory_json = {}
    if not factory_json :
        db = connectMySQL.connMySQL_mobileProduction()
        sql = 'SELECT id, name_cn FROM `s_factory`'
        logging.info(sql)
        c=db.cursor()
        c.execute(sql)  
        res= c.fetchall()
        for x in res:
            factory_json[x[0]] = x[1]
        
        c.close()
        db.close()
        
        #cache.add('factory_json', factory_json, settings.cache_expire_S)
    
    return factory_json
    
def getOsids(namec):
    db = connectMySQL.connMySQL_mobileProduction()
    sql = " SELECT id FROM `s_os` where name = '%s' " % namec
    logging.info(sql)
    c=db.cursor()
    c.execute(sql)  
    res= c.fetchall()
    resc = ",".join(res)
    c.close()
    db.close()
        
    return resc

def unique_list(seq, excludes=[]):  

    seen = set(excludes)  
    return [x for x in seq if x not in seen and not seen.add(x)] 


def getParnter(): 
    parnter_json = {}
    if not parnter_json :
        db = connectMySQL.connMySQL_mobileProduction()
        sql = 'SELECT pid, project_name, ph_id FROM `s_partner_new`'
        logging.info(sql)
        c=db.cursor()
        c.execute(sql)  
        res= c.fetchall()
        for x in res:
            parnter_json[x[0]] = [x[1], x[2]]
        
        c.close()
        db.close()
        
        #cache.add('parnter_json', parnter_json, settings.cache_expire_S)
        
    return parnter_json
    
def getFname(fid): 
    
    db = connectMySQL.connMySQL_mobileProduction()
    sql = 'SELECT name_cn FROM `s_factory` where id = %s' % fid
    #logging.info(sql)
    c=db.cursor()
    c.execute(sql)  
    res= c.fetchone()

        
    c.close()
    db.close()
    if res:    
        return res[0]
    else:
        return ""
        
def getJsondata(_tmpdate,table_name,st_datestr,et_datestr,_os_id,_dt,_pm):
    pmsql = ""
    if _pm == 1:
        pmsql = "1"
    else:
        pmsql = "2,8"
    
    if (_dt == "no") and (_pm == "no") :
        ossql = " and os_id = %s  " %  _os_id
    elif (_dt != "no") and (_pm == "no") :
        ossql = " and os_id = %s  and device_type = %s  " % (_os_id,_dt)
    elif (_dt == "no") and (_pm != "no") :
        ossql = " and os_id = %s  and partner_mode in (%s)  " % (_os_id,pmsql)
    elif (_dt != "no") and (_pm != "no") :
        ossql = " and os_id = %s and device_type = %s and partner_mode in (%s)  " % (_os_id,_dt,pmsql)
     
    
    db = connectMySQL.connMySQL_stat()
    sql = "SELECT apiresp FROM `%s` WHERE date = '%s' and  business_type=2  and pid_stat=1 and ver = 'ALL' %s " % (table_name,_tmpdate,ossql)
    #logging.info(sql)
    #print sql
    c=db.cursor()
    c.execute(sql)  
    res= c.fetchall()
    play_resptime_l = []
    play_times_l = []
    drew_resptime_l = []
    drew_times_l = []
    getVideoDetail_resptime_l = []
    getVideoDetail_times_l = []
    
    if res == None:
        return(0,0,0,0,0,0)
    
    for xy in res:
        
        
        try:    
            xyc = json_ly.read(str(xy[0]))
        except:
            xyc = ""
        
        #print xyc        
        try:
            play_resptime_one = xyc['layout/ipad2_2/play'][0]['resptime']
            play_resptime_l.append(float(play_resptime_one))
        except:
            pass
                
        try:            
            play_times_one = xyc['layout/ipad2_2/play'][0]['times']
            play_times_l.append(float(play_times_one))
        except:
            pass
        try:    
            drew_resptime_one = xyc['layout/ipad2_2/draw'][0]['resptime']
            drew_resptime_l.append(float(drew_resptime_one))
        except:
            pass
                
        try:    
            drew_times_one = xyc['layout/ipad2_2/draw'][0]['times']
            drew_times_l.append(float(drew_times_one))
        except:
            pass
                
        try:    
            getVideoDetail_resptime_one = xyc['getVideoDetail'][0]['resptime']
            getVideoDetail_resptime_l.append(float(getVideoDetail_resptime_one))
        except:
            pass
                    
        try:
            getVideoDetail_times_one = xyc['getVideoDetail'][0]['times']
            getVideoDetail_times_l.append(float(getVideoDetail_times_one))
        except:
            pass
    
    
        
    c.close()
    db.close()
    
    #print play_resptime
    #print getVideoDetail_resptime_l
    play_resptime = sum(play_resptime_l)
    play_times = sum(play_times_l)
    drew_resptime = sum(drew_resptime_l)
    drew_times = sum(drew_times_l)
    getVideoDetail_resptime = sum(getVideoDetail_resptime_l)
    getVideoDetail_times = sum(getVideoDetail_times_l)
    
    
    #print play_resptime     
    return (play_resptime,play_times,drew_resptime,drew_times,getVideoDetail_resptime,getVideoDetail_times)
    

def getJsondata_new(_sql):
    
    db = connectMySQL.connMySQL_stat()
    c=db.cursor()
    c.execute(_sql)  
    res= c.fetchall()
    play_resptime_l = []
    play_times_l = []
    drew_resptime_l = []
    drew_times_l = []
    getVideoDetail_resptime_l = []
    getVideoDetail_times_l = []
    
    #print _sql
    
    if res == None:
        #print "kill"
        return(0,0,0,0,0,0)
    else:
        for xy in res:
            
            
            try:    
                #xyc = json_ly.read(str(xy[0]))
                re_strc = str(xy[0]).replace("'","\"")
                xyc = json.loads(re_strc)
            except:
                xyc = ""
            
            
            try:
                #print 'zheli',xyc
                play_resptime_one = xyc['layout/ipad2_2/play'][0]['resptime']
                play_resptime_l.append(float(play_resptime_one))
                
            except:
                pass
                    
            try:            
                play_times_one = xyc['layout/ipad2_2/play'][0]['times']
                play_times_l.append(float(play_times_one))
            except:
                pass
            try:    
                drew_resptime_one = xyc['layout/ipad2_2/draw'][0]['resptime']
                drew_resptime_l.append(float(drew_resptime_one))
            except:
                pass
                    
            try:    
                drew_times_one = xyc['layout/ipad2_2/draw'][0]['times']
                drew_times_l.append(float(drew_times_one))
            except:
                pass
                    
            try:    
                getVideoDetail_resptime_one = xyc['getVideoDetail'][0]['resptime']
                getVideoDetail_resptime_l.append(float(getVideoDetail_resptime_one))
            except:
                pass
                        
            try:
                getVideoDetail_times_one = xyc['getVideoDetail'][0]['times']
                getVideoDetail_times_l.append(float(getVideoDetail_times_one))
            except:
                pass
        
        
            
        c.close()
        db.close()
        
        play_resptime = sum(play_resptime_l)
        play_times = sum(play_times_l)
        drew_resptime = sum(drew_resptime_l)
        drew_times = sum(drew_times_l)
        getVideoDetail_resptime = sum(getVideoDetail_resptime_l)
        getVideoDetail_times = sum(getVideoDetail_times_l)
        
        #print play_resptime,play_times,drew_resptime,drew_times,getVideoDetail_resptime,getVideoDetail_times
        return (play_resptime,play_times,drew_resptime,drew_times,getVideoDetail_resptime,getVideoDetail_times)

    
    

def getOsname(os_id): 
    
    db = connectMySQL.connMySQL_mobileProduction()
    sql = 'SELECT name FROM `s_os` where id = %s' % os_id
    #logging.info(sql)
    c=db.cursor()
    c.execute(sql)  
    res= c.fetchone()

        
    c.close()
    db.close()
    if res:    
        return res[0]
    else:
        return "unknow"
    
        
        
